#!/bin/bash
#record pv of hursing's blog. by liuhx

id="hursing"
interval=300
logFile="pvlog.txt"

url="http://blog.csdn.net/"$id"/article/list/"
viewmode="?viewmode=contents"
userAgent="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0"

function getMaxPage {
    response=`curl -s -A $userAgent $url"1"$viewmode`
	echo $response | grep -o "共[0-9]\+页</span>" | grep -o "[0-9]\+"
}

function getArticalTitles {
	page=1
	while [ $page -le $1 ]; do
		response=`curl -s -A $userAgent $url$page$viewmode`
		echo "$response" | grep -A 1 "link_title" | sed "/link_title/d;/--/d;s/^ \+//"
		let page+=1
	done
}

function queryReadTimes {
	page=$1
	date=`date +%y%m%d%H%M`
	zongshu=""
	cishu=""
	while [ $page -ge 1 ]; do
		response=`curl -s -A $userAgent $url$page$viewmode`
		if [ -z $zongshu ]; then
			zongshu=`echo "$response" | grep -o "<span>[0-9]\+次</span>" | grep -o "[0-9]\+"`
		fi
		pv=`echo "$response" | grep -o "阅读</a>([0-9]\+)" | grep -o "[0-9]\+"`
		cishu=$pv" "$cishu
		let page-=1
	done
	echo $date" "$zongshu" "$cishu
}

maxPage=`getMaxPage`
getArticalTitles $maxPage | tee -a $logFile
lastData=`queryReadTimes $maxPage`
echo "$lastData" | tee -a $logFile
lastData=($lastData)
while true; do
    sleep $interval
	result=`queryReadTimes $maxPage`
	echo "$result" >> $logFile
	newData=($result)
	i=1
	# if new Data greater than old, change the text color to red
	while [ $i -lt ${#newData[@]} ]; do
		if [ ${newData[$i]} -gt ${lastData[$i]} ]; then
			newData[$i]='\033[0;31;1m'${newData[$i]}'\033[0m'
		fi
		let i+=1
	done
	echo -e "${newData[*]}"
	lastData=($result)
done